#!/usr/bin/env node

/**
 * 发布前检查脚本
 * 确保包可以正常发布和使用
 */

import fs from 'fs';
import path from 'path';

const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));

console.log('🔍 ContentFlow Shared Library 发布前检查\n');

// 检查必要文件
const requiredFiles = [
  'dist/esm/index.js',
  'dist/cjs/index.cjs', 
  'dist/types/index.d.ts',
  'README.md',
  'LICENSE'
];

console.log('📁 检查必要文件:');
let allFilesExist = true;
for (const file of requiredFiles) {
  const exists = fs.existsSync(file);
  console.log(`  ${exists ? '✅' : '❌'} ${file}`);
  if (!exists) allFilesExist = false;
}

// 检查 package.json 配置
console.log('\n📦 检查 package.json 配置:');
const checks = [
  { key: 'name', value: packageJson.name, expected: '@contentflow/shared' },
  { key: 'version', value: packageJson.version, required: true },
  { key: 'main', value: packageJson.main, expected: 'dist/cjs/index.cjs' },
  { key: 'module', value: packageJson.module, expected: 'dist/esm/index.js' },
  { key: 'types', value: packageJson.types, expected: 'dist/types/index.d.ts' },
  { key: 'license', value: packageJson.license, expected: 'MIT' }
];

let configValid = true;
for (const check of checks) {
  if (check.expected) {
    const valid = check.value === check.expected;
    console.log(`  ${valid ? '✅' : '❌'} ${check.key}: ${check.value}`);
    if (!valid) configValid = false;
  } else if (check.required) {
    const valid = !!check.value;
    console.log(`  ${valid ? '✅' : '❌'} ${check.key}: ${check.value || '未设置'}`);
    if (!valid) configValid = false;
  }
}

// 检查导出配置
console.log('\n📤 检查导出配置:');
const exports = packageJson.exports;
if (exports) {
  const mainExport = exports['.'];
  if (mainExport) {
    console.log(`  ✅ 主导出: ${JSON.stringify(mainExport, null, 2)}`);
  } else {
    console.log(`  ❌ 缺少主导出配置`);
    configValid = false;
  }
  
  // 检查子模块导出
  const subExports = ['./storage', './platforms', './rpa'];
  for (const subExport of subExports) {
    if (exports[subExport]) {
      console.log(`  ✅ ${subExport}: 已配置`);
    } else {
      console.log(`  ⚠️  ${subExport}: 未配置（可选）`);
    }
  }
} else {
  console.log(`  ❌ 缺少 exports 配置`);
  configValid = false;
}

// 检查依赖
console.log('\n📚 检查依赖:');
const deps = packageJson.dependencies || {};
const devDeps = packageJson.devDependencies || {};
console.log(`  📦 生产依赖: ${Object.keys(deps).length} 个`);
console.log(`  🔧 开发依赖: ${Object.keys(devDeps).length} 个`);

// 检查构建产物大小
console.log('\n📊 检查构建产物大小:');
try {
  const esmSize = fs.statSync('dist/esm/index.js').size;
  const cjsSize = fs.statSync('dist/cjs/index.cjs').size;
  const typesSize = fs.statSync('dist/types/index.d.ts').size;
  
  console.log(`  📄 ESM: ${(esmSize / 1024).toFixed(1)} KB`);
  console.log(`  📄 CJS: ${(cjsSize / 1024).toFixed(1)} KB`);
  console.log(`  📄 Types: ${(typesSize / 1024).toFixed(1)} KB`);
  
  if (esmSize > 1024 * 1024) { // 1MB
    console.log(`  ⚠️  ESM 文件较大，考虑优化`);
  }
} catch (error) {
  console.log(`  ❌ 无法读取文件大小: ${error.message}`);
}

// 总结
console.log('\n📋 检查总结:');
if (allFilesExist && configValid) {
  console.log('✅ 所有检查通过，可以发布！');
  console.log('\n🚀 发布命令:');
  console.log('  npm publish');
  console.log('  # 或者');
  console.log('  pnpm publish');
  process.exit(0);
} else {
  console.log('❌ 检查失败，请修复问题后重试');
  if (!allFilesExist) {
    console.log('  - 请先运行构建: npm run build');
  }
  if (!configValid) {
    console.log('  - 请检查 package.json 配置');
  }
  process.exit(1);
}
